package com.plum.admin.modules.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plum.admin.common.exception.BaseException;
import com.plum.admin.modules.sys.entity.SysDict;
import com.plum.admin.modules.sys.entity.SysDictItem;
import com.plum.admin.modules.sys.mapper.SysDictMapper;
import com.plum.admin.modules.sys.service.ISysDictItemService;
import com.plum.admin.modules.sys.service.ISysDictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author 子丶沫
 * @since 2021-08-13
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {
    @Autowired
    private ISysDictItemService dictItemService;
    @Override
    public boolean deleteDict(List<String> idList) {
        idList.forEach(id->{
            List<SysDictItem> dictItemList = dictItemService.findDictItemList(id);
            if(CollUtil.isNotEmpty(dictItemList)){
                throw new BaseException(String.format("字典【%s】下存在字典值,无法删除",dictItemList.get(0).getDictName()));
            }
        });
        return baseMapper.deleteBatchIds(idList)>0;
    }

    @Override
    public List<SysDict> findDictList() {
        List<SysDict> dictList = baseMapper.selectList(Wrappers.<SysDict>lambdaQuery());
        return dictList.stream().peek(data->{
            data.setDictItemList(dictItemService.list(Wrappers.<SysDictItem>lambdaQuery()
                    .eq(SysDictItem::getDictId,data.getId()).eq(SysDictItem::getStatus,1)));
        }).collect(Collectors.toList());
    }
}
